from django.contrib import auth as django_auth
from django.db.models import Q
from rest_framework import exceptions
from rest_framework import generics
from rest_framework import permissions
from rest_framework import response
from rest_framework import views
import os
import rest_framework as drf
from django.contrib.postgres.search import TrigramSimilarity

from account import models as models_account
from book import models as models_book
from . import serializers

def modify_media_path(media_file):
    return  media_file.replace('/media', '')


class SearchView(views.APIView):
    serializer_class = serializers.BookBaseSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get(self,request):
        key = str(self.request.GET.get('key'))
        # book_list = models_book.Book.objects.filter(Q(name__icontains=key) |
        #                                             Q(university__icontains=key) |
        #                                             Q(author__icontains=key) |
        #                                             Q(version__icontains=key) |
        #                                             Q(shortname__icontains=key))
        # log_data = models_account.Logdata.objects.create(
        #     account_id=self.request.user.account.id,
        #     action_type='2',
        #     keyword=key,
        # )
        print('key=', key)
        if not key:
            drf.serializers.ValidationError({"detail": "关键词不能为空"})
        book_list=models_book.Book.objects.annotate(
            similarity=TrigramSimilarity('infos', key),
           ).filter(similarity__gt=0.01).order_by('-similarity')
        # filter(similarity__gt=0.3).

        log_data = models_account.Logdata.objects.create(
            account_id=request.user.account.id,
            action_type='2',
            keyword=key,
        )

        data = serializers.BookBaseSerializer(book_list,many=True).data
        for item in data:
            item['cover']=modify_media_path(item['cover'])

        return response.Response(data)

class HotestView(views.APIView):
    serializer_class = serializers.BookBaseSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get(self,request):
        book_list=models_book.Book.objects.all().order_by('-clicks')[0:10]

        data = serializers.BookBaseSerializer(book_list, many=True).data

        for item in data:
            item['cover']=modify_media_path(item['cover'])

        return response.Response(data)


class BookChapter(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        book_id = request.GET.get('book_id')
        try :
            book = models_book.Book.objects.get(id = book_id)
        except:
            raise drf.serializers.ValidationError({"detail": "未找到对应课本"})

        book.clicks=book.clicks+1
        book.save()
        chapter_list = models_book.Chapter.objects.filter(book = book)

        all_chapter = []

        for ch1 in chapter_list.filter(layers=1).order_by('index1'):
            x1={'id':ch1.id, 'title':ch1.title,'ti_count':ch1.ti_count,}
            print('x1=',x1)
            X2=[]
            for ch2 in chapter_list.filter(layers=2, index1=ch1.index1).order_by('index2'):

                x2={'id':ch2.id, 'title':ch2.title,'ti_count':ch2.ti_count,}
                X2.append(x2)
                X3=[]
                for ch3 in chapter_list.filter(layers=3, index2=ch2.index2).order_by('index3'):
                    x3={'id':ch3.id, 'title':ch3.title,'ti_count':ch3.ti_count,}
                    X3.append(x3)
                if X3!=[]:
                    x2['item']=X3
            if X2!=[]:
                x1['item']=X2
            all_chapter.append([x1])
        print(all_chapter)
        # log the action------------
        models_account.Logdata.objects.create(
            book_id=book_id,
            action_type='3',
            account_id=request.user.account.id,
        )


        return response.Response(all_chapter)



class TiView(views.APIView):
    permission_classes = (permissions.IsAuthenticated,)
    def get(self,request):
        chapter_id = request.GET.get('chapter_id')
        ti_number = request.GET.get('ti_number')

        if chapter_id == None or int(chapter_id) <= 0:
            raise drf.serializers.ValidationError({"detail": "章节参数无效"})
        elif ti_number == None or int(ti_number) <= 0:
            raise drf.serializers.ValidationError({"detail": "题目编号参数无效"})

        try:
            chapter = models_book.Chapter.objects.get(id = chapter_id)
        except:
            raise drf.serializers.ValidationError({"detail": "未找到对应章节"})


        xiaoti_list = models_book.Ti.objects.filter(chapter=chapter,
                                                    ti_number=ti_number,
                                                    ).order_by('xiaoti_number')
        if not xiaoti_list.exists():
            raise drf.serializers.ValidationError({"detail": "未找到对应题目"})

        ti_list = []
        data={"title":None,"ti":ti_list}
        for xiaoti in xiaoti_list.filter(is_title=True):
            if xiaoti.is_title == True:
                data["title"] = xiaoti.question.url
                data["id"] =xiaoti.id

                break

        for xiaoti in xiaoti_list:
            if xiaoti.is_title != True:
                xiaoti_data=serializers.XiaoTiSerializer(xiaoti).data
                xiaoti_data['qa']=modify_media_path(xiaoti_data['qa'])
                ti_list.append(xiaoti_data)
        data["ti"]=ti_list

        #更新搜题次数
        self.update_account_search(request.user.account,xiaoti_list[0].id)

        return response.Response(data)


    def update_account_search(self,account,ti_id):
        log_data = models_account.Logdata.objects.create(
            account_id = account.id,
            action_type = '1',
            ti_id = ti_id,
        )

